package com.rk.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rk.admin.domain.User;
import com.rk.admin.mapper.UserMapper;
import com.rk.admin.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录
     * @param username
     * @return
     */
    @Override
    public User login(String username){
        //条件查询
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<User>();
        //where username=#{username}
        lqw.eq(User::getUsername,username);
        return userMapper.selectOne(lqw);
    }


    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @Override
    public Boolean UserAdd(User user) {
        //对密码进行加密处理
        //设置加密密码
        String mdPwd = new Md5Hash(user.getPassword(),
                user.getUsername() + user.getPassword(),
                100).toString();
        System.out.println("加密密码:"+mdPwd);
        user.setPassword(mdPwd);
        return userMapper.UserAdd(user)>0;
    }

    /**
     * 通过id删除用户
     *
     * @param uid
     * @return
     */
    @Override
    public Boolean deletebyuid(int uid) {
        return userMapper.deleteById(uid)>0;
    }

    /**
     * 根据id查找用户
     * @param uid
     * @return
     */
    @Override
    public User findbyuid(int uid) {
        return userMapper.queryById(uid);
    }

    /**
     * 通过uid修改用户
     *
     * @param user
     * @return
     */
    @Override
    public Boolean updatebyuid(User user) {
        String mdPwd = new Md5Hash(user.getPassword(),
                user.getUsername() + user.getPassword(),
                100).toString();
        user.setPassword(mdPwd);
        return userMapper.updatebyuid(user)>0;
    }


    /**
         * 条件分页查询
         *
         * @param page
         * @param limit
         * @param username
         * @return
    */
    @Override
    public IPage<User> selectPage ( int page, int limit, String username,String role){
            IPage<User> pageinfo = new Page<>(page, limit);
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            //根据id降序
            //lqw.orderByDesc(User::getUid);
            //根据教师姓名进行条件查询

            if("1".equals(role))//如果是中级用户，就不查询高级用户  叫条件role!=2
                lqw.ne(User::getRole,2);

            if (!"".equals(username) && username != null) {
                lqw.like(User::getUsername, username);
            }
            //分页查询数据
            userMapper.selectPage(pageinfo, lqw);

            return pageinfo;
        }

}
